{{define "content"}}
<style>
.editor-fullscreen {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9999 !important;
    background: white !important;
    padding: 20px !important;
}

.editor-fullscreen .editor-container {
    height: calc(100vh - 80px) !important;
}

.editor-toolbar {
    transition: all 0.2s ease;
}

.editor-toolbar:hover {
    background: rgba(255,255,255,1) !important;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* Editor Status Bar Styling */
.editor-status-bar {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 11px;
    transition: all 0.2s ease;
}

.editor-status-bar:hover {
    background: rgba(248,249,250,1) !important;
    box-shadow: 0 -2px 8px rgba(0,0,0,0.05);
}

/* Custom Tooltip Styling */
.tooltip {
    z-index: 10001 !important; /* Above editor toolbar */
}

.tooltip .tooltip-inner {
    background-color: #ffffff !important;
    color: #212529 !important;
    border: 1px solid #dee2e6 !important;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
    font-size: 12px !important;
    padding: 8px 12px !important;
    border-radius: 6px !important;
    font-weight: 500 !important;
}

.tooltip .tooltip-arrow::before {
    border-top-color: #ffffff !important;
    border-bottom-color: #ffffff !important;
    border-left-color: #ffffff !important;
    border-right-color: #ffffff !important;
}

.tooltip.bs-tooltip-bottom .tooltip-arrow::before {
    border-bottom-color: #ffffff !important;
}

.tooltip.bs-tooltip-top .tooltip-arrow::before {
    border-top-color: #ffffff !important;
}

.tooltip.bs-tooltip-end .tooltip-arrow::before {
    border-right-color: #ffffff !important;
}

.tooltip.bs-tooltip-start .tooltip-arrow::before {
    border-left-color: #ffffff !important;
}

/* Spinning animation for reset button */
.spin {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* Enhanced Editor Button Styling */
#reset-editor-btn, #fullscreen-btn {
    font-weight: 500;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

#reset-editor-btn:hover, #fullscreen-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(13, 110, 253, 0.25);
}

#reset-editor-btn:active, #fullscreen-btn:active {
    transform: translateY(0);
}

#reset-editor-btn:disabled, #fullscreen-btn:disabled {
    transform: none;
    cursor: not-allowed;
    opacity: 0.6;
}

#reset-editor-btn::before, #fullscreen-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}

#reset-editor-btn:hover::before, #fullscreen-btn:hover::before {
    left: 100%;
}

/* Custom reset modal styling */
.reset-modal .modal-content {
    border: none;
    border-radius: 12px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
}

.reset-modal .modal-header {
    background: linear-gradient(135deg, #dc3545, #c82333);
    color: white;
    border-radius: 12px 12px 0 0;
    border-bottom: none;
}

.reset-modal .modal-title {
    font-weight: 600;
}

.reset-modal .btn-close {
    filter: invert(1);
}

.reset-modal .code-preview {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 12px;
    max-height: 120px;
    overflow-y: auto;
}

.reset-modal .btn-reset-confirm {
    background: linear-gradient(135deg, #dc3545, #c82333);
    border: none;
    font-weight: 500;
    transition: all 0.2s ease;
}

.reset-modal .btn-reset-confirm:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}
</style>
<div class="row mb-4">
    <div class="col">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="/">Challenges</a></li>
                <li class="breadcrumb-item active">Challenge {{.Challenge.ID}}</li>
            </ol>
        </nav>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-5">
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Challenge {{.Challenge.ID}}: {{.Challenge.Title}}</h5>
                <span class="badge bg-primary badge-{{.Challenge.Difficulty | lower}}">{{.Challenge.Difficulty}}</span>
            </div>
            <div class="card-body">
                {{if .HasAttempted}}
                <div class="alert alert-success mb-3">
                    <i class="bi bi-check-circle-fill"></i> You've previously attempted this challenge.
                    {{if .ExistingSolution}}
                    <br>Your existing solution has been loaded in the editor.
                    {{end}}
                </div>
                {{end}}
                
                <div class="markdown-content" id="challenge-description"></div>
            </div>
        </div>
    </div>
    <div class="col-md-7">
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="editorTabs" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="solution-tab" data-bs-toggle="tab" href="#solution" role="tab">Solution</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="tests-tab" data-bs-toggle="tab" href="#tests" role="tab">Tests</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="results-tab" data-bs-toggle="tab" href="#results" role="tab">Results</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="scoreboard-tab" data-bs-toggle="tab" href="#scoreboard" role="tab">
                            <i class="bi bi-trophy me-1"></i>Scoreboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="hints-tab" data-bs-toggle="tab" href="#hints" role="tab">
                            <i class="bi bi-lightbulb me-1"></i>Hints
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="learning-tab" data-bs-toggle="tab" href="#learning" role="tab">Learnings</a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content">
                    <div class="tab-pane fade show active" id="solution" role="tabpanel">
                                                    <div class="editor-wrapper position-relative">
                            <!-- Editor Toolbar -->
                            <div class="editor-toolbar position-absolute top-0 end-0 p-2 d-flex align-items-center gap-2" style="z-index: 10; background: rgba(255,255,255,0.95); border-radius: 0 0 0 8px; border-left: 1px solid #dee2e6; border-bottom: 1px solid #dee2e6;">
                                <!-- Save Status -->
                                <span id="save-indicator" class="badge bg-success d-none">
                                    <i class="bi bi-check2"></i> Saved
                                </span>
                                <span id="saving-indicator" class="badge bg-warning d-none">
                                    <i class="bi bi-arrow-repeat"></i> Saving...
                                </span>

                                <!-- Fullscreen Button -->
                                <button class="btn btn-outline-primary btn-sm" id="fullscreen-btn" 
                                        data-bs-toggle="tooltip" data-bs-placement="top" 
                                        title="Enter fullscreen mode (ESC to exit)">
                                    <i class="bi bi-arrows-fullscreen"></i>
                                </button>

                                <!-- Reset Button -->
                                <button class="btn btn-outline-primary btn-sm" id="reset-editor-btn" 
                                        data-bs-toggle="tooltip" data-bs-placement="top" 
                                        title="Reset code to original template">
                                    <span id="reset-icon">
                                        <i class="bi bi-arrow-counterclockwise"></i>
                                    </span>
                                    <span id="reset-spinner" class="d-none">
                                        <i class="bi bi-arrow-repeat spin"></i>
                                    </span>
                                </button>
                            </div>

                            <!-- Editor Status Bar -->
                            <div class="editor-status-bar position-absolute bottom-0 end-0 px-2 py-1" style="z-index: 10; background: rgba(248,249,250,0.95); border-radius: 4px 0 0 0; border-left: 1px solid #dee2e6; border-top: 1px solid #dee2e6;">
                                <small class="text-muted" id="editor-position">
                                    <i class="bi bi-cursor-text me-1"></i>
                                    Ln <span id="line-number">1</span>, Col <span id="col-number">1</span>
                                </small>
                            </div>

                            <div id="editor" class="editor-container"></div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="tests" role="tabpanel">
                        <div id="test-editor" class="editor-container"></div>
                    </div>
                    <div class="tab-pane fade" id="results" role="tabpanel">
                        <div id="test-results" class="p-3">
                            <div class="alert alert-info">Run your code to see test results.</div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="scoreboard" role="tabpanel">
                        <div id="scoreboard-content" class="p-3">
                            <div class="text-center mb-4">
                                <div class="mb-3">
                                    <i class="bi bi-trophy" style="font-size: 2.5rem; color: #ffd700;"></i>
                                </div>
                                <h5 class="mb-2">Challenge {{.Challenge.ID}} Scoreboard</h5>
                                <p class="text-muted mb-3">Developers who solved this challenge</p>
                            </div>

                            <!-- Mini Scoreboard -->
                            <div id="mini-scoreboard-container">
                                <div class="text-center py-4" id="loading-mini-scoreboard">
                                    <div class="spinner-border text-primary mb-2" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="text-muted small">Loading participants...</p>
                                </div>
                            </div>

                            <!-- View Full Scoreboard Button -->
                            <div class="text-center mt-4">
                                <a href="/scoreboard/{{.Challenge.ID}}" class="btn btn-primary">
                                    <i class="bi bi-eye me-2"></i>View Full Scoreboard
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="hints" role="tabpanel">
                        <div id="hints-content" class="p-3">
                            <div class="text-center mb-4">
                                <i class="bi bi-lightbulb" style="font-size: 2.5rem; color: #ffc107;"></i>
                                <h5 class="mb-2">Progressive Hints</h5>
                                <p class="text-muted mb-3">Click "Show Next Hint" to reveal hints one by one</p>
                            </div>
                            
                            <div id="hints-container">
                                <!-- Hints will be dynamically loaded here -->
                            </div>
                            
                            <div class="text-center mt-4">
                                <button class="btn btn-outline-warning" id="show-hint-btn">
                                    <i class="bi bi-lightbulb me-2"></i>Show Next Hint
                                </button>
                                <button class="btn btn-outline-secondary ms-2 d-none" id="reset-hints-btn">
                                    <i class="bi bi-arrow-counterclockwise me-2"></i>Reset Hints
                                </button>
                            </div>
                            
                            <div class="mt-3 text-center">
                                <small class="text-muted">
                                    <span id="hints-progress">0</span> of <span id="total-hints">0</span> hints revealed
                                </small>
                            </div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="learning" role="tabpanel">
                        <div id="learning-materials" class="p-3 markdown-content">
                            <!-- Learning materials will be loaded here -->
                        </div>
                    </div>
                </div>
                <div class="d-flex justify-content-between mt-3">
                    <button class="btn btn-primary" id="run-button">
                        <span class="spinner-border spinner-border-sm d-none" id="run-spinner" role="status" aria-hidden="true"></span>
                        <span id="run-text">Run Tests</span>
                    </button>
                    <button class="btn btn-success" id="submit-button">
                        <span class="spinner-border spinner-border-sm d-none" id="submit-spinner" role="status" aria-hidden="true"></span>
                        <span id="submit-text">Submit Solution</span>
                    </button>
                </div>
                
                <!-- Status message toast -->
                <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 5">
                    <div id="statusToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="toast-header">
                            <strong class="me-auto" id="toast-title">Notification</strong>
                            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                        <div class="toast-body" id="toast-message">
                            Message content
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Premium Sponsors Section -->
<div class="row mb-4">
    <div class="col">
        <div class="text-center py-3">
            <div class="sponsors-container" id="challenge-premium-sponsors">
                <!-- Premium sponsor logos will appear here -->
                <div class="text-muted">
                    <i class="bi bi-building me-2"></i>
                    <span class="small">
                        <a href="https://github.com/sponsors/RezaSi" target="_blank" class="text-decoration-none text-muted">
                            Sponsored by our premium partners
                        </a>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Reset Confirmation Modal -->
<div class="modal fade reset-modal" id="resetModal" tabindex="-1" aria-labelledby="resetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resetModalLabel">
                    <i class="bi bi-exclamation-triangle me-2"></i>Reset Code to Original Template
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <p class="mb-2"><strong>Are you sure you want to reset your code?</strong></p>
                    <p class="text-muted small mb-3">This action will permanently delete all your changes and restore the original template.</p>
                </div>
                
                <div class="mb-3">
                    <h6 class="text-danger mb-2">
                        <i class="bi bi-trash me-1"></i>What will be lost:
                    </h6>
                    <ul class="list-unstyled small text-muted mb-0">
                        <li><i class="bi bi-x-circle text-danger me-1"></i>All your current code changes</li>
                        <li><i class="bi bi-x-circle text-danger me-1"></i>Auto-saved progress in browser</li>
                        <li><i class="bi bi-x-circle text-danger me-1"></i>Any work since your last submission</li>
                    </ul>
                </div>

                <div class="mb-3">
                    <h6 class="text-success mb-2">
                        <i class="bi bi-arrow-clockwise me-1"></i>What will be restored:
                    </h6>
                    <div class="code-preview p-2">
                        <div class="small text-muted mb-1">Original template preview:</div>
                        <pre id="template-preview" class="mb-0"></pre>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg me-1"></i>Cancel
                </button>
                <button type="button" class="btn btn-danger btn-reset-confirm" id="confirmResetBtn">
                    <span id="confirm-reset-text">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>Reset Code
                    </span>
                    <span id="confirm-reset-spinner" class="d-none">
                        <i class="bi bi-arrow-repeat spin me-1"></i>Resetting...
                    </span>
                </button>
            </div>
        </div>
    </div>
</div>

{{end}}

{{define "scripts"}}
<script>
    // Challenge data from server
    const challengeData = {
        id: {{.Challenge.ID}},
        title: "{{.Challenge.Title}}",
        description: `{{.Challenge.Description}}`,
        template: `{{.Challenge.Template}}`,
        testFile: `{{.Challenge.TestFile}}`,
        learningMaterials: `{{.Challenge.LearningMaterials}}`,
        hints: `{{.Challenge.Hints}}`
    };
    
    // User data and existing solution, properly escaped for JavaScript
    const hasAttempted = {{if .HasAttempted}}true{{else}}false{{end}};
    // Safely define existingSolution variable
    let existingSolution = null;
    {{if .ExistingSolution}}
    existingSolution = `{{js .ExistingSolution}}`;
    {{end}}

    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Markdown for description
        const descriptionElement = document.getElementById('challenge-description');
        renderMarkdownAndCleanup(challengeData.description, descriptionElement);

        // Initialize Markdown for learning materials
        const learningElement = document.getElementById('learning-materials');
        renderMarkdown(challengeData.learningMaterials, learningElement);

        // Initialize learning materials highlighting
        initLearningMaterials('learning-materials', challengeData.id);

        // Initialize hints system
        initializeHints(challengeData.hints);

        // Initialize code editor for solution
        const editor = ace.edit("editor");
        editor.setTheme("ace/theme/chrome");
        editor.session.setMode("ace/mode/golang");
        
        // Load content from template or existing solution
        if (existingSolution) {
            editor.setValue(existingSolution);
        } else {
            editor.setValue(challengeData.template);
        }
        
        editor.clearSelection();

        // Auto-save functionality with visual indicators
        let saveTimeout;
        let isOriginalTemplate = true;
        
        // Check if we have saved code to determine initial state
        const savedCode = localStorage.getItem(`challenge_${challengeData.id}_code`);
        if (savedCode && !existingSolution) {
            editor.setValue(savedCode, 1);
            isOriginalTemplate = false;
            showSaveIndicator();
        }
        
                editor.session.on('change', function() {
            clearTimeout(saveTimeout);
            isOriginalTemplate = false;

            // Show saving indicator
            showSavingIndicator();

            saveTimeout = setTimeout(() => {
                localStorage.setItem(`challenge_${challengeData.id}_code`, editor.getValue());
                showSaveIndicator();
            }, 1000);
        });

        // Update line/column numbers on cursor movement
        editor.selection.on('changeCursor', function() {
            updateEditorPosition();
        });

        // Initial position update
        updateEditorPosition();

        // Initialize tooltips
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Reset button functionality
        document.getElementById('reset-editor-btn').addEventListener('click', function() {
            // Show template preview in modal
            const templatePreview = document.getElementById('template-preview');
            const previewText = existingSolution || challengeData.template;
            templatePreview.textContent = previewText.substring(0, 200) + (previewText.length > 200 ? '...' : '');
            
            // Show the custom modal
            const resetModal = new bootstrap.Modal(document.getElementById('resetModal'));
            resetModal.show();
        });

        // Confirm reset button in modal
        document.getElementById('confirmResetBtn').addEventListener('click', function() {
            const resetButton = document.getElementById('reset-editor-btn');
            const resetIcon = document.getElementById('reset-icon');
            const resetSpinner = document.getElementById('reset-spinner');
            const confirmText = document.getElementById('confirm-reset-text');
            const confirmSpinner = document.getElementById('confirm-reset-spinner');
            
            // Show loading states
            resetIcon.classList.add('d-none');
            resetSpinner.classList.remove('d-none');
            confirmText.classList.add('d-none');
            confirmSpinner.classList.remove('d-none');
            resetButton.disabled = true;
            this.disabled = true;
            
            // Simulate reset process with delay for better UX
            setTimeout(() => {
                // Clear saved code
                localStorage.removeItem(`challenge_${challengeData.id}_code`);
                
                // Reset to template
                if (existingSolution) {
                    editor.setValue(existingSolution);
                } else {
                    editor.setValue(challengeData.template);
                }
                editor.clearSelection();
                
                isOriginalTemplate = true;
                hideSaveIndicators();
                
                // Hide modal
                const resetModal = bootstrap.Modal.getInstance(document.getElementById('resetModal'));
                resetModal.hide();
                
                // Reset button states
                resetIcon.classList.remove('d-none');
                resetSpinner.classList.add('d-none');
                confirmText.classList.remove('d-none');
                confirmSpinner.classList.add('d-none');
                resetButton.disabled = false;
                this.disabled = false;
                
                // Show success message
                setTimeout(() => {
                    showToast('Success', 'Code successfully reset to original template', 'success');
                }, 200);
            }, 800); // Small delay for better UX feedback
        });

        // Fullscreen functionality
        document.getElementById('fullscreen-btn').addEventListener('click', function() {
            const editorWrapper = document.querySelector('.editor-wrapper');
            const icon = this.querySelector('i');
            const tooltip = bootstrap.Tooltip.getInstance(this);
            
            if (!document.fullscreenElement && !editorWrapper.classList.contains('editor-fullscreen')) {
                // Enter fullscreen mode
                editorWrapper.classList.add('editor-fullscreen');
                icon.className = 'bi bi-fullscreen-exit';
                this.setAttribute('data-bs-original-title', 'Exit fullscreen mode (ESC)');
                if (tooltip) {
                    tooltip.dispose();
                    new bootstrap.Tooltip(this, { 
                        title: 'Exit fullscreen mode (ESC)',
                        placement: 'top'
                    });
                }
                
                // Resize editor to fit fullscreen
                setTimeout(() => {
                    editor.resize();
                }, 100);
                
                // Add escape key listener
                document.addEventListener('keydown', handleEscapeKey);
            } else {
                // Exit fullscreen mode
                exitFullscreen();
            }
        });

        function exitFullscreen() {
            const editorWrapper = document.querySelector('.editor-wrapper');
            const fullscreenBtn = document.getElementById('fullscreen-btn');
            const icon = fullscreenBtn.querySelector('i');
            const tooltip = bootstrap.Tooltip.getInstance(fullscreenBtn);
            
            editorWrapper.classList.remove('editor-fullscreen');
            icon.className = 'bi bi-arrows-fullscreen';
            fullscreenBtn.setAttribute('data-bs-original-title', 'Enter fullscreen mode (ESC to exit)');
            if (tooltip) {
                tooltip.dispose();
                new bootstrap.Tooltip(fullscreenBtn, { 
                    title: 'Enter fullscreen mode (ESC to exit)',
                    placement: 'top'
                });
            }
            
            // Resize editor back to normal
            setTimeout(() => {
                editor.resize();
            }, 100);
            
            // Remove escape key listener
            document.removeEventListener('keydown', handleEscapeKey);
        }

        function handleEscapeKey(event) {
            if (event.key === 'Escape') {
                exitFullscreen();
            }
        }

        // Helper functions for save indicators
        function showSavingIndicator() {
            document.getElementById('saving-indicator').classList.remove('d-none');
            document.getElementById('save-indicator').classList.add('d-none');
        }
        
        function showSaveIndicator() {
            document.getElementById('saving-indicator').classList.add('d-none');
            document.getElementById('save-indicator').classList.remove('d-none');
            
            // Hide save indicator after 2 seconds
            setTimeout(() => {
                if (!isOriginalTemplate) {
                    document.getElementById('save-indicator').classList.add('d-none');
                }
            }, 2000);
        }
        
        function hideSaveIndicators() {
            document.getElementById('saving-indicator').classList.add('d-none');
            document.getElementById('save-indicator').classList.add('d-none');
        }

        // Update line and column numbers in status bar
        function updateEditorPosition() {
            if (!editor) return;
            
            const cursor = editor.getCursorPosition();
            const lineNumber = cursor.row + 1; // Ace uses 0-based indexing
            const colNumber = cursor.column + 1;
            
            document.getElementById('line-number').textContent = lineNumber;
            document.getElementById('col-number').textContent = colNumber;
        }

        // Initialize code editor for tests
        const testEditor = ace.edit("test-editor");
        testEditor.setTheme("ace/theme/chrome");
        testEditor.session.setMode("ace/mode/golang");
        testEditor.setValue(challengeData.testFile);
        testEditor.setReadOnly(true);
        testEditor.clearSelection();
        
        // Toast initialization
        const toastElement = document.getElementById('statusToast');
        let toast;
        if (typeof bootstrap !== 'undefined') {
            toast = new bootstrap.Toast(toastElement, { delay: 5000 });
        } else {
            // Fallback for when Bootstrap JS isn't loaded
            toast = {
                show: function() {
                    toastElement.classList.add('show');
                    setTimeout(() => {
                        toastElement.classList.remove('show');
                    }, 5000);
                }
            };
        }
        
        // Toast helper function
        function showToast(title, message, type = 'info') {
            document.getElementById('toast-title').textContent = title;
            document.getElementById('toast-message').textContent = message;
            
            // Remove any existing color classes
            toastElement.classList.remove('bg-success', 'bg-danger', 'bg-warning', 'bg-info', 'text-white');
            
            // Add appropriate color class
            if (type === 'success') {
                toastElement.classList.add('bg-success', 'text-white');
            } else if (type === 'error') {
                toastElement.classList.add('bg-danger', 'text-white');
            } else if (type === 'warning') {
                toastElement.classList.add('bg-warning');
            } else {
                toastElement.classList.add('bg-info', 'text-white');
            }
            
            toast.show();
        }

        // Handle Run Tests button
        const runButton = document.getElementById('run-button');
        const runSpinner = document.getElementById('run-spinner');
        const runText = document.getElementById('run-text');
        
        runButton.addEventListener('click', function() {
            const code = editor.getValue();
            const resultsTab = document.getElementById('results-tab');
            const resultsPane = document.getElementById('results');
            const resultsDiv = document.getElementById('test-results');
            
            // Disable button and show spinner
            runButton.disabled = true;
            runSpinner.classList.remove('d-none');
            runText.textContent = 'Running...';
            
            // Switch to results tab
            resultsTab.click();
            
            // Show loading indicator
            resultsDiv.innerHTML = `
                <div class="d-flex justify-content-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
                <p class="text-center mt-2">Running tests...</p>
            `;
            
            // Call API to run tests
            fetch('/api/run', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    challengeId: challengeData.id,
                    code: code
                })
            })
            .then(response => response.json())
            .then(data => {
                // Format and display test results
                let outputHtml = '';
                
                if (data.passed) {
                    outputHtml += `<div class="alert alert-success mb-3">
                        <h4 class="alert-heading">All Tests Passed! 🎉</h4>
                        <p>Execution time: ${data.executionMs}ms</p>
                    </div>`;
                    showToast('Success', 'All tests passed!', 'success');
                } else {
                    outputHtml += `<div class="alert alert-danger mb-3">
                        <h4 class="alert-heading">Tests Failed</h4>
                        <p>Review the output below to fix your solution.</p>
                    </div>`;
                    showToast('Tests Failed', 'Some tests didn\'t pass. Check the results tab.', 'warning');
                }
                
                // Format test output
                outputHtml += `<div class="card">
                    <div class="card-header">Test Output</div>
                    <div class="card-body">
                        <pre><code class="language-go">${escapeHtml(data.output)}</code></pre>
                    </div>
                </div>`;
                
                resultsDiv.innerHTML = outputHtml;
                
                // Apply syntax highlighting
                document.querySelectorAll('pre code').forEach((el) => {
                    hljs.highlightElement(el);
                });
                
                // Re-enable button and hide spinner
                runButton.disabled = false;
                runSpinner.classList.add('d-none');
                runText.textContent = 'Run Tests';
            })
            .catch(error => {
                resultsDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <h4 class="alert-heading">Error</h4>
                        <p>${error.message}</p>
                    </div>
                `;
                
                showToast('Error', 'Failed to run tests: ' + error.message, 'error');
                
                // Re-enable button and hide spinner
                runButton.disabled = false;
                runSpinner.classList.add('d-none');
                runText.textContent = 'Run Tests';
            });
        });

        // Handle Submit Solution button
        const submitButton = document.getElementById('submit-button');
        const submitSpinner = document.getElementById('submit-spinner');
        const submitText = document.getElementById('submit-text');
        
        // Handle Scoreboard tab loading
        const scoreboardTab = document.getElementById('scoreboard-tab');
        let scoreboardLoaded = false;
        
        if (scoreboardTab) {
            scoreboardTab.addEventListener('click', function() {
                if (!scoreboardLoaded) {
                    loadMiniScoreboard();
                    scoreboardLoaded = true;
                }
            });
        }
        
        function loadMiniScoreboard() {
            const container = document.getElementById('mini-scoreboard-container');
            const loadingDiv = document.getElementById('loading-mini-scoreboard');
            
            // Fetch scoreboard data
            fetch(`/api/scoreboard/${challengeData.id}`)
                .then(response => response.json())
                .then(data => {
                    loadingDiv.style.display = 'none';
                    
                    if (data.length === 0) {
                        container.innerHTML = `
                            <div class="text-center py-4">
                                <i class="bi bi-trophy-fill text-muted" style="font-size: 2rem;"></i>
                                <p class="text-muted mt-2 mb-0">No submissions yet</p>
                                <small class="text-muted">Be the first to solve this challenge!</small>
                            </div>
                        `;
                    } else {
                        let scoreboardHtml = `
                            <div class="mb-3">
                                <div class="row text-center">
                                    <div class="col-4">
                                        <div class="text-primary">
                                            <i class="bi bi-people-fill"></i>
                                        </div>
                                        <div class="fw-bold">${data.length}</div>
                                        <small class="text-muted">Participants</small>
                                    </div>
                                    <div class="col-4">
                                        <div class="text-success">
                                            <i class="bi bi-check-circle-fill"></i>
                                        </div>
                                        <div class="fw-bold">100%</div>
                                        <small class="text-muted">Success Rate</small>
                                    </div>
                                    <div class="col-4">
                                        <div class="text-warning">
                                            <i class="bi bi-speedometer2"></i>
                                        </div>
                                        <div class="fw-bold">${challengeData.difficulty || 'Medium'}</div>
                                        <small class="text-muted">Difficulty</small>
                                    </div>
                                </div>
                            </div>
                            <div class="border rounded">
                        `;
                        
                        // Show top 5 participants
                        const topParticipants = data.slice(0, 5);
                        topParticipants.forEach((participant, index) => {
                            const rank = index + 1;
                            let rankBadge = '';
                            
                            if (rank === 1) rankBadge = '🥇';
                            else if (rank === 2) rankBadge = '🥈';
                            else if (rank === 3) rankBadge = '🥉';
                            else rankBadge = `#${rank}`;
                            
                            const borderClass = index < topParticipants.length - 1 ? 'border-bottom' : '';
                            
                            scoreboardHtml += `
                                <div class="p-3 ${borderClass}">
                                    <div class="d-flex align-items-center">
                                        <div class="me-3 text-center" style="min-width: 40px;">
                                            <span class="badge bg-primary">${rankBadge}</span>
                                        </div>
                                        <img src="https://github.com/${participant.username}.png" 
                                             class="rounded-circle me-3" 
                                             style="width: 32px; height: 32px;" 
                                             alt="${participant.username}">
                                        <div class="flex-grow-1">
                                            <div class="fw-bold">${participant.username}</div>
                                            <small class="text-muted">${formatDate(participant.submittedAt)}</small>
                                        </div>
                                        <div class="text-end">
                                            <span class="badge bg-success">SOLVED</span>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        scoreboardHtml += '</div>';
                        
                        if (data.length > 5) {
                            scoreboardHtml += `
                                <div class="text-center mt-3">
                                    <small class="text-muted">... and ${data.length - 5} more participants</small>
                                </div>
                            `;
                        }
                        
                        container.innerHTML = scoreboardHtml;
                    }
                })
                .catch(error => {
                    console.error('Error loading mini scoreboard:', error);
                    loadingDiv.style.display = 'none';
                    container.innerHTML = `
                        <div class="text-center py-4">
                            <i class="bi bi-exclamation-triangle text-warning" style="font-size: 2rem;"></i>
                            <p class="text-muted mt-2 mb-0">Error loading scoreboard</p>
                            <small class="text-muted">Please try refreshing the page</small>
                        </div>
                    `;
                });
        }
        
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US', {
                month: 'short',
                day: 'numeric'
            });
        }

        submitButton.addEventListener('click', function() {
            const code = editor.getValue();
            const username = document.getElementById('username').value;
            
            if (!username) {
                showToast('Error', 'Please enter your GitHub username before submitting.', 'error');
                return;
            }
            
            // Disable button and show spinner
            submitButton.disabled = true;
            submitSpinner.classList.remove('d-none');
            submitText.textContent = 'Submitting...';
            
            // Submit solution
            fetch('/api/submissions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    challengeId: challengeData.id,
                    code: code
                })
            })
            .then(response => response.json())
            .then(data => {
                // Switch to results tab to show test results
                document.getElementById('results-tab').click();
                
                // Format and display test results
                let outputHtml = '';
                
                if (data.passed) {
                    outputHtml += `<div class="alert alert-success mb-3">
                        <h4 class="alert-heading">Solution Submitted Successfully! 🎉</h4>
                        <p>All tests passed. Execution time: ${data.executionMs}ms</p>
                        <hr>
                        <p class="mb-0">Follow the instructions below to submit your solution to the public scoreboard.</p>
                    </div>`;
                    
                    showToast('Success', 'Your solution was submitted successfully and all tests passed!', 'success');
                    
                    // Add file system submission instructions
                    outputHtml += `<div class="alert alert-info mb-3">
                        <h5>🚀 Next Steps: Create a Pull Request</h5>
                        <p class="mb-3">To contribute your solution to the project and appear on the public scoreboard, follow these steps:</p>
                        
                        <div class="d-flex gap-2 mb-3">
                            <button class="btn btn-primary" id="save-filesystem-btn">💾 Save to Filesystem</button>
                            <button class="btn btn-secondary" id="copy-commands-btn">📋 Copy Git Commands</button>
                        </div>
                        
                        <div class="accordion" id="submissionAccordion">
                            <div class="accordion-item">
                                <h2 class="accordion-header">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#step1" aria-expanded="true">
                                        <strong>Step 1: Save Your Solution Locally</strong>
                                    </button>
                                </h2>
                                <div id="step1" class="accordion-collapse collapse show" data-bs-parent="#submissionAccordion">
                                    <div class="accordion-body">
                                        <p>Click "💾 Save to Filesystem" above to save your solution directly to the correct location.</p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="accordion-item">
                                <h2 class="accordion-header">
                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#step2">
                                        <strong>Step 2: Commit and Push to Your Fork</strong>
                                    </button>
                                </h2>
                                <div id="step2" class="accordion-collapse collapse" data-bs-parent="#submissionAccordion">
                                    <div class="accordion-body">
                                        <p>Run these Git commands to save your changes to your forked repository:</p>
                                        <div class="bg-dark text-light p-3 rounded">
                                            <pre><code>$ cd ../../../
$ git add challenge-${challengeData.id}/submissions/${username}/
$ git commit -m "Add solution for Challenge ${challengeData.id} by ${username}"
$ git push origin main</code></pre>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="accordion-item">
                                <h2 class="accordion-header">
                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#step3">
                                        <strong>Step 3: Create Pull Request on GitHub</strong>
                                    </button>
                                </h2>
                                <div id="step3" class="accordion-collapse collapse" data-bs-parent="#submissionAccordion">
                                    <div class="accordion-body">
                                        <ol>
                                            <li>Go to your forked repository on GitHub: <code>https://github.com/${username}/go-interview-practice</code></li>
                                            <li>You should see a banner saying "This branch is X commits ahead of RezaSi:main"</li>
                                            <li>Click the <strong>"Contribute"</strong> button next to it</li>
                                            <li>Click <strong>"Open pull request"</strong></li>
                                            <li>Add a title like: <code>Add solution for Challenge ${challengeData.id} by ${username}</code></li>
                                            <li>Click <strong>"Create pull request"</strong></li>
                                        </ol>
                                        <div class="alert alert-success mt-3">
                                            <strong>🎉 That's it!</strong> Your solution will be reviewed and merged, appearing on the public scoreboard.
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-3">
                            <small class="text-muted">
                                <strong>💡 Tip:</strong> Make sure you forked the repository first. If you cloned the original repository directly, 
                                you won't be able to push changes or create pull requests.
                            </small>
                        </div>
                    </div>`;
                } else {
                    outputHtml += `<div class="alert alert-warning mb-3">
                        <h4 class="alert-heading">Solution Submitted with Failing Tests</h4>
                        <p>Review the output below to fix your solution.</p>
                    </div>`;
                    
                    showToast('Warning', 'Your solution was submitted but some tests failed.', 'warning');
                }
                
                // Format test output
                outputHtml += `<div class="card">
                    <div class="card-header">Test Output</div>
                    <div class="card-body">
                        <pre><code class="language-go">${escapeHtml(data.testOutput)}</code></pre>
                    </div>
                </div>`;
                
                document.getElementById('test-results').innerHTML = outputHtml;
                
                // Apply syntax highlighting
                document.querySelectorAll('pre code').forEach((el) => {
                    hljs.highlightElement(el);
                });
                
                // Add copy functionality for the commands
                const copyBtn = document.getElementById('copy-commands-btn');
                if (copyBtn) {
                    copyBtn.addEventListener('click', function() {
                        const commandText = document.querySelector('.bg-dark pre code').innerText;
                        navigator.clipboard.writeText(commandText)
                            .then(() => {
                                showToast('Success', 'Commands copied to clipboard!', 'success');
                                copyBtn.textContent = 'Copied!';
                                setTimeout(() => {
                                    copyBtn.textContent = 'Copy Commands';
                                }, 2000);
                            })
                            .catch(err => {
                                showToast('Error', 'Failed to copy: ' + err, 'error');
                            });
                    });
                }
                
                // Add functionality to save directly to filesystem
                const saveFilesystemBtn = document.getElementById('save-filesystem-btn');
                if (saveFilesystemBtn) {
                    saveFilesystemBtn.addEventListener('click', function() {
                        this.disabled = true;
                        this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';
                        
                        fetch('/api/save-to-filesystem', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                username: username,
                                challengeId: challengeData.id,
                                code: code
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                showToast('Success', 'Solution saved to filesystem!', 'success');
                                
                                // Show comprehensive next steps including PR creation
                                let nextStepsHtml = `
                                    <div class="mt-3 p-3 bg-light rounded">
                                        <h6>✅ Solution Saved! Next Steps:</h6>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6 class="text-primary">1. Commit & Push to Your Fork:</h6>
                                                <div class="bg-dark text-light p-2 rounded small">
                                                    <pre><code>cd ../../../
git add challenge-${challengeData.id}/submissions/${username}/
git commit -m "Add solution for Challenge ${challengeData.id} by ${username}"
git push origin main</code></pre>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <h6 class="text-success">2. Create Pull Request:</h6>
                                                <ol class="small">
                                                    <li>Go to <a href="https://github.com/${username}/go-interview-practice" target="_blank">your fork on GitHub</a></li>
                                                    <li>Click the "Contribute" button</li>
                                                    <li>Click "Open pull request"</li>
                                                    <li>Add title: "Add solution for Challenge ${challengeData.id}"</li>
                                                    <li>Submit your PR! 🎉</li>
                                                </ol>
                                            </div>
                                        </div>
                                        <div class="alert alert-info mt-2 small">
                                            <strong>🔗 Direct Link:</strong> After pushing, GitHub will often show a banner with a direct "Compare & pull request" button for convenience.
                                        </div>
                                    </div>
                                `;
                                
                                // Insert after the button
                                this.parentNode.insertAdjacentHTML('afterend', nextStepsHtml);
                            } else {
                                showToast('Error', data.message || 'Failed to save to filesystem', 'error');
                            }
                            
                            this.disabled = false;
                            this.textContent = 'Saved!';
                            setTimeout(() => {
                                this.textContent = 'Save to Filesystem';
                            }, 2000);
                        })
                        .catch(error => {
                            showToast('Error', 'Failed to save: ' + error.message, 'error');
                            this.disabled = false;
                            this.textContent = 'Save to Filesystem';
                        });
                    });
                }
                
                // Re-enable button and hide spinner
                submitButton.disabled = false;
                submitSpinner.classList.add('d-none');
                submitText.textContent = 'Submit Solution';
            })
            .catch(error => {
                showToast('Error', 'Failed to submit solution: ' + error.message, 'error');
                
                // Re-enable button and hide spinner
                submitButton.disabled = false;
                submitSpinner.classList.add('d-none');
                submitText.textContent = 'Submit Solution';
            });
        });
        
        // Enhanced renderMarkdown function that cleans up scoreboard links
        function renderMarkdownAndCleanup(markdownText, targetElement) {
            if (!markdownText || !targetElement) return;
            
            // Clean up scoreboard-related content from the markdown
            let cleanedMarkdown = markdownText
                // Remove "View the Scoreboard" links (case insensitive)
                .replace(/\[view\s+the\s+scoreboard\]/gi, '')
                .replace(/\(\s*scoreboard\.md\s*\)/gi, '')
                // Remove standalone scoreboard references
                .replace(/^.*scoreboard\.md.*$/gmi, '')
                // Remove empty lines that might be left behind
                .replace(/\n\s*\n\s*\n/g, '\n\n')
                // Clean up any remaining scoreboard links
                .replace(/\[.*?scoreboard.*?\]\(.*?\)/gi, '')
                .trim();
            
            // Use the existing renderMarkdown function
            renderMarkdown(cleanedMarkdown, targetElement);
        }

        // Helper function to escape HTML
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Hints system functionality
        function initializeHints(hintsMarkdown) {
            const hintsContainer = document.getElementById('hints-container');
            const showHintBtn = document.getElementById('show-hint-btn');
            const resetHintsBtn = document.getElementById('reset-hints-btn');
            const hintsProgress = document.getElementById('hints-progress');
            const totalHints = document.getElementById('total-hints');
            
            if (!hintsContainer || !showHintBtn || !resetHintsBtn) return;
            
            // Parse hints from markdown
            const hints = parseHintsFromMarkdown(hintsMarkdown);
            let currentHintIndex = 0;
            
            // Update total hints count
            totalHints.textContent = hints.length;
            
            // Show hint button functionality
            showHintBtn.addEventListener('click', function() {
                if (currentHintIndex < hints.length) {
                    showHint(hints[currentHintIndex], currentHintIndex + 1);
                    currentHintIndex++;
                    updateHintsProgress();
                    
                    // Show reset button when at least one hint is shown
                    if (currentHintIndex > 0) {
                        resetHintsBtn.classList.remove('d-none');
                    }
                    
                    // Hide show button when all hints are revealed
                    if (currentHintIndex >= hints.length) {
                        showHintBtn.classList.add('d-none');
                    }
                }
            });
            
            // Reset hints button functionality
            resetHintsBtn.addEventListener('click', function() {
                currentHintIndex = 0;
                hintsContainer.innerHTML = '';
                showHintBtn.classList.remove('d-none');
                resetHintsBtn.classList.add('d-none');
                updateHintsProgress();
            });
            
            function showHint(hint, hintNumber) {
                const hintElement = document.createElement('div');
                hintElement.className = 'alert alert-info hint-item mb-3';
                hintElement.style.animation = 'slideIn 0.3s ease-in-out';
                hintElement.innerHTML = `
                    <div class="d-flex align-items-start">
                        <div class="flex-shrink-0">
                            <span class="badge bg-warning text-dark me-2">Hint ${hintNumber}</span>
                        </div>
                        <div class="flex-grow-1 markdown-content">
                            ${hint.content}
                        </div>
                    </div>
                `;
                hintsContainer.appendChild(hintElement);
                
                // Scroll hint into view
                hintElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
            
            function updateHintsProgress() {
                hintsProgress.textContent = currentHintIndex;
            }
            
            function parseHintsFromMarkdown(markdown) {
                if (!markdown || markdown.trim() === '' || markdown.includes('*No hints available')) {
                    return [];
                }
                
                const hints = [];
                const lines = markdown.split('\n');
                let currentHint = null;
                
                for (const line of lines) {
                    const trimmedLine = line.trim();
                    
                    // Check if this is a hint header (## Hint N:)
                    const hintMatch = trimmedLine.match(/^##\s+Hint\s+\d+:\s*(.*)$/i);
                    if (hintMatch) {
                        // Save previous hint if exists
                        if (currentHint) {
                            hints.push(currentHint);
                        }
                        
                        // Start new hint
                        currentHint = {
                            title: hintMatch[1],
                            content: ''
                        };
                    } else if (currentHint && trimmedLine && !trimmedLine.startsWith('#')) {
                        // Add content to current hint
                        if (currentHint.content) {
                            currentHint.content += '\n';
                        }
                        currentHint.content += line;
                    }
                }
                
                // Add the last hint
                if (currentHint) {
                    hints.push(currentHint);
                }
                
                // Convert markdown content to HTML using proper markdown parser
                hints.forEach(hint => {
                    const tempDiv = document.createElement('div');
                    renderMarkdown(hint.content.trim(), tempDiv);
                    hint.content = tempDiv.innerHTML;
                });
                
                return hints;
            }

        }
    });
</script>
{{end}} 